Photo by Tonia Kraakman on Unsplash
Mount Cook, Canterbury, New Zealand
SwiftUI → UIKit’s ViewController 用 UIViewControllerRepresentable 協定
SwiftUI → UIKit’s View 用 UIViewRepresentable 協定
cheat sheet
struct CustomView: UIViewRepresentable {
func makeUIView(context: Context) -> some UIView {
// Return the UIView object
}
func updateUIView(_ uiView: some UIView, context: Context) {
// Update the view
}
}
有加 delegate 的話
textView.delegate = context.coordinator
func makeCoordinator() -> Coordinator {
Coordinator($text)
}
class Coordinator: NSObject, UITextViewDelegate {
var text: Binding<String>
init(_ text: Binding<String>) {
self.text = text
}
func textViewDidChange(_ textView: UITextView) {
self.text.wrappedValue = textView.text
}
}
實作例子 🌰
import SwiftUI
import WebKit
struct WebView: UIViewRepresentable {
var url: URL
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ webView: WKWebView, context: Context) {
let request = URLRequest(url: url)
webView.load(request)
}
}
private struct ResourceLinkRow: View {
var title: String
var webViewUrl: String
var isPDF: Bool
@State private var showWebView = false
func checkUrl() -> URL {
var url = URL(string: webViewUrl)
if isPDF {
url = Bundle.main.url(forResource: webViewUrl, withExtension: "pdf")
}
return url!
}
var body: some View {
HStack(spacing: 16) {
Button {
showWebView.toggle()
} label: {
Text(title)
.padding(.vertical, 12)
.padding(.horizontal, 24)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
.sheet(isPresented: $showWebView) {
WebView(url: checkUrl())
}
}
.padding(.horizontal)
}
}
ResourceLinkRow(title: "iOS App Dev Tutorials", webViewUrl: "https://developer.apple.com/tutorials/app-dev-training", isPDF: false)
咖啡廳門口有人抽雪茄,整個咖啡廳有雪茄味,今天到這。收工
一人抽雪茄,大家一起吸。
詳細請看下面兩篇文章 👋🏻
使用 UIViewRepresentable 協定 讓你輕鬆建立 SwiftUI TextView
利用 UIViewControllerRepresentable 協定 在 SwiftUI 存取相簿並使用相機